package com.apigen.platform.controller;

import com.apigen.platform.common.Result;
import com.apigen.platform.dto.ApiEndpointRequest;
import com.apigen.platform.service.IApiEndpointService;
import com.apigen.platform.vo.ApiEndpointVO;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * API端点管理控制器
 *
 * @author API Generator Platform
 * @since 2024-09-24
 */
@Slf4j
@RestController
@RequestMapping("/api/endpoints")
@RequiredArgsConstructor
@Validated
@Tag(name = "API端点管理", description = "API端点的增删改查、批量生成等管理接口")
public class ApiEndpointController {

    private final IApiEndpointService apiEndpointService;

    @PostMapping
    @Operation(summary = "创建API端点", description = "创建新的API端点配置")
    public Result<Long> createEndpoint(@Valid @RequestBody ApiEndpointRequest request) {
        try {
            Long endpointId = apiEndpointService.createEndpoint(request);
            return Result.success(endpointId);
        } catch (Exception e) {
            log.error("创建API端点失败: {}", e.getMessage());
            return Result.error("创建端点失败: " + e.getMessage());
        }
    }

    @PutMapping("/{endpointId}")
    @Operation(summary = "更新API端点", description = "更新指定的API端点配置")
    public Result<Void> updateEndpoint(
            @Parameter(description = "端点ID") @PathVariable Long endpointId,
            @Valid @RequestBody ApiEndpointRequest request) {
        try {
            request.setEndpointId(endpointId);
            Boolean result = apiEndpointService.updateEndpoint(request);
            if (result) {
                return Result.success("更新端点成功");
            } else {
                return Result.error("更新端点失败");
            }
        } catch (Exception e) {
            log.error("更新API端点失败: {}", e.getMessage());
            return Result.error("更新端点失败: " + e.getMessage());
        }
    }

    @DeleteMapping
    @Operation(summary = "删除API端点", description = "批量删除API端点")
    public Result<Void> deleteEndpoints(@Parameter(description = "端点ID列表") @RequestBody List<Long> endpointIds) {
        try {
            Boolean result = apiEndpointService.deleteEndpoints(endpointIds);
            if (result) {
                return Result.success("删除端点成功");
            } else {
                return Result.error("删除端点失败");
            }
        } catch (Exception e) {
            log.error("删除API端点失败: {}", e.getMessage());
            return Result.error("删除端点失败: " + e.getMessage());
        }
    }

    @GetMapping("/{endpointId}")
    @Operation(summary = "获取API端点详情", description = "根据ID获取API端点的详细信息")
    public Result<ApiEndpointVO> getEndpointDetail(@Parameter(description = "端点ID") @PathVariable Long endpointId) {
        try {
            ApiEndpointVO endpoint = apiEndpointService.getEndpointDetail(endpointId);
            return Result.success(endpoint);
        } catch (Exception e) {
            log.error("获取API端点详情失败: {}", e.getMessage());
            return Result.error("获取端点详情失败: " + e.getMessage());
        }
    }

    @GetMapping
    @Operation(summary = "获取API端点列表", description = "分页获取API端点列表，支持按项目、表、HTTP方法筛选")
    public Result<Page<ApiEndpointVO>> getEndpointList(
            @Parameter(description = "项目ID") @RequestParam(required = false) Long projectId,
            @Parameter(description = "表ID") @RequestParam(required = false) Long tableId,
            @Parameter(description = "HTTP方法") @RequestParam(required = false) String httpMethod,
            @Parameter(description = "当前页", example = "1") @RequestParam(defaultValue = "1") Long current,
            @Parameter(description = "每页大小", example = "10") @RequestParam(defaultValue = "10") Long size) {
        try {
            Page<ApiEndpointVO> page = apiEndpointService.getEndpointList(projectId, tableId, httpMethod, current, size);
            return Result.success(page);
        } catch (Exception e) {
            log.error("获取API端点列表失败: {}", e.getMessage());
            return Result.error("获取端点列表失败: " + e.getMessage());
        }
    }

    @PostMapping("/generate/table/{tableId}")
    @Operation(summary = "根据表生成API端点", description = "根据指定表自动生成标准的CRUD API端点")
    public Result<List<ApiEndpointVO>> generateEndpointsByTable(
            @Parameter(description = "表ID") @PathVariable Long tableId,
            @Parameter(description = "项目ID") @RequestParam Long projectId) {
        try {
            List<ApiEndpointVO> endpoints = apiEndpointService.generateEndpointsByTable(tableId, projectId);
            return Result.success(endpoints);
        } catch (Exception e) {
            log.error("根据表生成API端点失败: {}", e.getMessage());
            return Result.error("生成端点失败: " + e.getMessage());
        }
    }

    @PostMapping("/generate/batch")
    @Operation(summary = "批量生成API端点", description = "根据多个表批量生成API端点")
    public Result<List<ApiEndpointVO>> batchGenerateEndpoints(
            @Parameter(description = "表ID列表") @RequestBody List<Long> tableIds,
            @Parameter(description = "项目ID") @RequestParam Long projectId) {
        try {
            List<ApiEndpointVO> endpoints = apiEndpointService.batchGenerateEndpoints(tableIds, projectId);
            return Result.success(endpoints);
        } catch (Exception e) {
            log.error("批量生成API端点失败: {}", e.getMessage());
            return Result.error("批量生成端点失败: " + e.getMessage());
        }
    }

    @GetMapping("/check-path")
    @Operation(summary = "检查端点路径唯一性", description = "检查指定的端点路径和HTTP方法组合是否已存在")
    public Result<Boolean> checkEndpointPath(
            @Parameter(description = "端点路径") @RequestParam String endpointPath,
            @Parameter(description = "HTTP方法") @RequestParam String httpMethod,
            @Parameter(description = "项目ID") @RequestParam Long projectId,
            @Parameter(description = "排除的端点ID") @RequestParam(required = false) Long excludeEndpointId) {
        try {
            Boolean isUnique = apiEndpointService.isEndpointPathUnique(endpointPath, httpMethod, projectId, excludeEndpointId);
            return Result.success(isUnique);
        } catch (Exception e) {
            log.error("检查端点路径唯一性失败: {}", e.getMessage());
            return Result.error("检查路径失败: " + e.getMessage());
        }
    }

    @GetMapping("/statistics")
    @Operation(summary = "获取API统计信息", description = "获取指定项目的API端点统计信息")
    public Result<IApiEndpointService.ApiStatistics> getApiStatistics(
            @Parameter(description = "项目ID") @RequestParam Long projectId) {
        try {
            IApiEndpointService.ApiStatistics statistics = apiEndpointService.getApiStatistics(projectId);
            return Result.success(statistics);
        } catch (Exception e) {
            log.error("获取API统计信息失败: {}", e.getMessage());
            return Result.error("获取统计信息失败: " + e.getMessage());
        }
    }
}











